// VoiceSignatureRequest,
import { VoiceSignatureResponse } from '../types/speechRecognition';

// API基础URL - 使用相对路径，通过vite代理转发
const NODE_API_BASE_URL = import.meta.env.VITE_NODE_API_BASE_URL;

/**
 * 获取腾讯云语音识别签名
 */
export const getVoiceSignature = async (userId: number): Promise<VoiceSignatureResponse> => {
  try {
    const response = await fetch(`${NODE_API_BASE_URL}/api/voiceforText/voice-signature`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userId }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data: VoiceSignatureResponse = await response.json();
    
    if (!data.success) {
      throw new Error('Failed to get voice signature');
    }

    // 详细检查返回的签名信息
    // console.log('🔐 后端返回的完整数据结构:', JSON.stringify(data, null, 2));
    // console.log('🔐 后端返回的签名信息:');
    // console.log('  - appId:', data.data.appId, '(类型:', typeof data.data.appId, ')');
    // console.log('  - secretId:', data.data.secretId ? data.data.secretId.substring(0, 12) + '...' : '❌ 未提供', '(类型:', typeof data.data.secretId, ')');
    // console.log('  - timestamp:', data.data.timestamp, '(类型:', typeof data.data.timestamp, ')');
    // console.log('  - expired:', data.data.expired, '(类型:', typeof data.data.expired, ')');
    // console.log('  - signature:', data.data.signature ? data.data.signature.substring(0, 20) + '...' : '❌ 未提供', '(类型:', typeof data.data.signature, ')');
    // console.log('  - engine_model_type:', data.data.engine_model_type, '(类型:', typeof data.data.engine_model_type, ')');
    // console.log('  - voice_format:', data.data.voice_format, '(类型:', typeof data.data.voice_format, ')');
    // console.log('  - needvad:', data.data.needvad, '(类型:', typeof data.data.needvad, ')');
    // console.log('  - voiceId:', data.data.voiceId, '(类型:', typeof data.data.voiceId, ')');
    // console.log('  - wsUrl:', data.data.wsUrl, '(类型:', typeof data.data.wsUrl, ')');
    
    // 验证必需字段
    const requiredFields = ['appId', 'secretId', 'timestamp', 'expired', 'signature', 'voiceId', 'wsUrl', 'queryParams'];
    const missingFields = requiredFields.filter(field => {
      const value = data.data[field as keyof typeof data.data];
      return value === undefined || value === null || value === '';
    });
    
    if (missingFields.length > 0) {
      // console.error('❌ 缺少必需的签名字段:', missingFields);
      // console.error('❌ 实际接收到的字段:', Object.keys(data.data));
      console.error('missing required fields',missingFields);
      // console.error(missingFields);
      // throw new Error(`缺少必需的签名字段: ${missingFields.join(', ')}`);
      throw new Error(`missing required fields: ${missingFields.join(', ')}`);
    }
    
    // 检查签名是否已过期
    const now = Math.floor(Date.now() / 1000);
    if (now >= data.data.expired) {
      // console.error('❌ 签名已过期:', {
      //   现在时间: now,
      //   过期时间: data.data.expired,
      //   相差秒数: now - data.data.expired
      // });
      console.error('signature expired');
      // throw new Error('签名已过期，请重新获取');
      throw new Error('signature expired');
    }
    
    // console.log('✅ 签名验证通过，有效期剩余:', data.data.expired - now, '秒');

    return data;
  } catch (error) {
    console.error('Error getting voice signature:', error);
    throw error;
  }
};

/**
 * 验证签名是否有效（检查是否过期）
 */
export const isSignatureValid = (signature: VoiceSignatureResponse['data']): boolean => {
  const now = Math.floor(Date.now() / 1000);
  return now < signature.expired;
};

/**
 * 获取WebSocket错误码对应的错误信息
 */
const getWebSocketErrorMessage = (code: number): string => {
  const errorMessages: Record<number, string> = {
    1000: '正常关闭',
    1001: '端点离开',
    1002: '协议错误',
    1003: '不支持的数据',
    1005: '未收到状态码',
    1006: '连接异常关闭 - 可能是网络问题或服务器拒绝连接',
    1007: '数据类型错误',
    1008: '策略违规',
    1009: '消息过大',
    1010: '扩展协商失败',
    1011: '服务器错误',
    1015: 'TLS握手失败'
  };
  return errorMessages[code] || `未知错误码: ${code}`;
};

/**
 * 创建WebSocket连接用于实时语音识别
 * 使用后端返回的完整参数和预构建的查询参数
 */
export const createVoiceRecognitionWebSocket = (
  signatureData: VoiceSignatureResponse['data'],
  options: {
    voiceId?: string;
    onMessage?: (data: any) => void;
    onError?: (error: Event) => void;
    onClose?: (event: CloseEvent) => void;
  } = {}
): WebSocket => {
  // console.log('🎤 使用后端返回的完整WebSocket配置:');
  // console.log('  - appId:', signatureData.appId);
  // console.log('  - secretId:', signatureData.secretId.substring(0, 12) + '...');
  // console.log('  - timestamp:', signatureData.timestamp);
  // console.log('  - expired:', signatureData.expired);
  // console.log('  - signature:', signatureData.signature);
  // console.log('  - voiceId:', signatureData.voiceId);
  // console.log('  - wsUrl:', signatureData.wsUrl);
  // console.log('  - queryParams:', signatureData.queryParams);
  
  // 直接使用后端构建的查询参数
  const queryParams = signatureData.queryParams;
  const paramPairs: string[] = [];
  
  // 将后端返回的queryParams转换为查询字符串
  for (const [key, value] of Object.entries(queryParams)) {
    paramPairs.push(`${key}=${value}`);
  }
  
  const queryString = paramPairs.join('&');
  
  // 构建最终的WebSocket URL - 直接使用后端提供的参数
  const wsUrl = `${signatureData.wsUrl}?${queryString}`;
  
  // console.log('🎤 完整的WebSocket URL:', wsUrl);
  
  // 创建WebSocket连接
  const ws = new WebSocket(wsUrl);
  
  // 设置事件处理器
  ws.onopen = (event) => {
    // console.log('🎤 WebSocket连接已建立');
    // console.log('连接事件:', event);
  };
  
  ws.onmessage = (event) => {
    // console.log('🎤 收到WebSocket消息:', event.data);
    try {
      const data = JSON.parse(event.data);
      options.onMessage?.(data);
    } catch (error) {
      // console.error('解析WebSocket消息失败:', error);
      console.error('parse WebSocket message failed',error);
      options.onError?.(event);
    }
  };
  
  ws.onerror = (event) => {
    // console.error('🎤 WebSocket错误:', event);
    console.error('WebSocket error',event);
    options.onError?.(event);
  };
  
  ws.onclose = (event) => {
    // console.log('🎤 WebSocket连接已关闭');
    // console.log('关闭码:', event.code, '原因:', getWebSocketErrorMessage(event.code));
    // console.log('关闭原因:', event.reason);
    options.onClose?.(event);
  };
  
  return ws;
}; 